#ifndef _BUFFER_POOL_H_
#define _BUFFER_POOL_H_

#include <vector>
#include "threadlock.h"
namespace utils
{
	template<class mt_policy = threadlock::multi_threaded_local>
	class CBufferPool 
	{
	public:		
		CBufferPool(int secsize):m_secsize(secsize)
		{			
		}

		~CBufferPool()
		{
			Close();
		}
		int GetSecSize() const 
		{
			return m_secsize;
		}
		void Close()
		{
			threadlock::autoguard<mt_policy> guard(&m_lock);
			m_availpool.clear();

			for (auto it = m_allpool.begin(); it != m_allpool.end(); ++it)
			{
				delete [] (*it);
			}
			m_allpool.clear();
		}

		char* Pop()
		{
			threadlock::autoguard<mt_policy> guard(&m_lock);
			
			char* ret = NULL;

			if(m_availpool.size() > 0 )
			{
				ret = m_availpool.back();
				m_availpool.pop_back();
			}
			else
			{
				ret = new char[m_secsize];
				m_allpool.push_back(ret	);
			}
	
			return ret;
		}
		void Push(char* buff)
		{
			threadlock::autoguard<mt_policy> guard(&m_lock);
			m_availpool.push_back(buff);
		}
	private:
		mt_policy m_lock;
		std::vector<char*> m_availpool;		
		std::vector<char*> m_allpool;
		const int m_secsize;
		
	};


	typedef CBufferPool<threadlock::multi_threaded_local> CThreadSafeBuffPool;
}
#endif